<html>
  <script>
    // Adapted from keyGMusic by Intars Students and Brad Lambeth
    // https://chrome.google.com/webstore/detail/gejnmibjdbgahfcddkmphaopmdgjcepa

    var keyshort = {

      // Init keyshort object
      init: function(){

        keyshort.acpTabID = null;
        keyshort.debug = false;

        keyshort.defaults = {
          "play"      : '{"modifiers":["control","alt","shift"],"keycode":191,"enabled":true}',
          "prev"      : '{"modifiers":["control","alt","shift"],"keycode":37,"enabled":true}',
          "next"      : '{"modifiers":["control","alt","shift"],"keycode":39,"enabled":true}'
        };

        // Wait for keyup in another tab
        chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
          if (request.method == "keyup"){

            // Check localStorage for missing link
            for(var toggle in keyshort.defaults){
              if (!localStorage[toggle]){
                localStorage[toggle] = keyshort.defaults[toggle];
                keyshort.log("localStorage fix: " + toggle + " reset");
              }
            }

            var t = null;
            var dismatch = null;
            var action = null;

            // Is this combo valid?
            try{

              for(var toggle in localStorage){
                dismatch = false;
                t = JSON.parse(localStorage[toggle]);

                if (typeof(t["enabled"]) == "undefined"){
                  t["enabled"] = true;
                  localStorage[toggle] = JSON.stringify(t);
                }

                if (!t["enabled"])
                  continue;

                if (t["modifiers"].length != request["modifiers"].length)
                  continue;

                for(var i in t["modifiers"]){
                  if (t["modifiers"][i] != request["modifiers"][i]){
                    dismatch = true;
                    break;
                  }
                }

                if (dismatch)
                  continue;

                if (t["keycode"] != request["keycode"])
                  continue;

                action = toggle;
              }

            }catch(e){}

            // Yup, it is, so continue toggling
            if (action){

              keyshort.log("Toggling '" + action + "' ...");

              if (keyshort.acpTabID != null){

                keyshort.toggle(action);

              }else{

                keyshort.log("Searching for Google Music Player ...");

                chrome.windows.getAll({populate: true}, function(windows) {
                  var pattern = 'https?\:\/\/music\.google\.com\/music\/listen.*';
                  for (var window = 0; window < windows.length; window++) {
                    for (var i = 0; i < windows[window].tabs.length; i++) {
                      if (windows[window].tabs[i].url.match(pattern)) {
                        keyshort.acpTabID = windows[window].tabs[i].id;
                        keyshort.log("The groove is found!");
                        keyshort.toggle(action);
                        break;
                      }
                    }
                  }

		  if (keyshort.acpTabID == null){
                    keyshort.log("Where is groove?!");
                  }

                });

              }

            }

          }

          sendResponse({});
        });

        // When tab is removed, check if it wasn't Google Music Player tab
        chrome.tabs.onRemoved.addListener(function(tabID){
          if (tabID == keyshort.acpTabID){
            keyshort.log("Google Music Player tab removed!");
            keyshort.acpTabID = null;
          }
        });

      },

      // Debugging is half of victory!
      log: function(msg){
        if (keyshort.debug && msg){
          console.log("keyshort ---> " + msg);
        }
      },

      // Send toggle to Google Music Player tab
      toggle: function(request){
        if (request){
          chrome.tabs.sendRequest(keyshort.acpTabID, {method : "CloudPlayer", action: request}, function(response){
            if (response.result == 200){
              keyshort.log("Toggled '" + request + "' !");
            }else{
              keyshort.acpTabID = null;
              keyshort.log("Couldn't toggle '" + request +"' !");
            }
          });
        }
      }

    }

    window.addEventListener("load", function(e) { keyshort.init(e); }, false);
  </script>
</html>
